#include "AudioPlayerWidget.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QFileDialog>
#include <QDateTime>
#include <QAudioOutput>
#include <QMessageBox>
#include <QGroupBox>
#include <QStyle>
#include <QApplication>
#include <QRadioButton>
#include <QComboBox>
#include <QDialog>
#include <QGridLayout>
#include <QCheckBox>
#include <QDir>

AudioPlayerWidget::AudioPlayerWidget(QWidget *parent) : QWidget(parent),
    m_player(new QMediaPlayer(this)),
    m_fileEdit(new QLineEdit(this)),
    m_fileButton(new QPushButton("选择文件", this)),
    m_restSpin(new QSpinBox(this)),
    m_stimSpin(new QSpinBox(this)),
    m_repeatSpin(new QSpinBox(this)),
    m_startButton(new QPushButton("开始", this)),
    m_startStimulusButton(new QPushButton("开始刺激", this)),
    m_stopStimulusButton(new QPushButton("停止刺激", this)),
    m_volumeSlider(new QSlider(Qt::Horizontal, this)),
    m_volumeLabel(new QLabel("音量:", this)),
    m_currentCycle(0), m_totalCycles(0),
    m_loopEnabled(false),
    m_playbackRate(1.0),
    m_ttsManager(new TextToSpeechManager(this)),
    m_textEdit(new QTextEdit(this)),
    m_speakButton(new QPushButton("播放文本", this)),
    m_stopSpeakButton(new QPushButton("停止播放", this)),
    m_ttsStatusLabel(new QLabel("就绪", this)),
    m_progressBar(new QProgressBar(this)),
    m_statusIndicator(new QLabel(this)),
    m_totalDuration(0),
    m_remainingTime(0),
    m_stimulusState(StimulusState::Idle),
    m_currentProgress(0)
{
    // 设置音频输出
    QAudioOutput *audioOutput = new QAudioOutput(this);
    m_player->setAudioOutput(audioOutput);

    // 设置控件样式和属性
    m_fileEdit->setPlaceholderText("音频文件路径...");
    m_fileEdit->setObjectName("fileEdit");

    m_fileButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_FileDialogStart));
    m_fileButton->setObjectName("fileButton");

    m_restSpin->setRange(0, 3600);
    m_restSpin->setValue(90);
    m_restSpin->setPrefix("  ");
    m_restSpin->setSuffix(" 秒  ");

    m_stimSpin->setRange(1, 3600);
    m_stimSpin->setValue(72);
    m_stimSpin->setPrefix("  ");
    m_stimSpin->setSuffix(" 秒  ");

    m_repeatSpin->setRange(1, 100);
    m_repeatSpin->setValue(1);
    m_repeatSpin->setPrefix("  ");
    m_repeatSpin->setSuffix(" 次  ");

    // 设置音量滑块
    m_volumeSlider->setRange(0, 100);
    m_volumeSlider->setValue(70);  // 默认音量70%
    m_volumeSlider->setTickPosition(QSlider::TicksBelow);
    m_volumeSlider->setTickInterval(10);
    m_volumeSlider->setObjectName("volumeSlider");
    audioOutput->setVolume(0.7);  // 设置初始音量

    // 设置开始刺激按钮
    m_startStimulusButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_MediaPlay));
    m_startStimulusButton->setObjectName("startStimulusButton");
    m_startStimulusButton->setMinimumWidth(100);

    // 设置停止刺激按钮
    m_stopStimulusButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_MediaStop));
    m_stopStimulusButton->setObjectName("stopStimulusButton");
    m_stopStimulusButton->setMinimumWidth(100);
    m_stopStimulusButton->setEnabled(false); // 初始状态禁用

    // 设置进度条
    m_progressBar->setRange(0, 100);
    m_progressBar->setValue(0);
    m_progressBar->setFormat("%v%");
    m_progressBar->setTextVisible(true);
    m_progressBar->setObjectName("stimulusProgressBar");

    // 设置状态指示器
    m_statusIndicator->setFixedSize(24, 24);
    m_statusIndicator->setAlignment(Qt::AlignCenter);
    m_statusIndicator->setStyleSheet("background-color: #a0a0a0; border-radius: 12px;"); // 灰色表示未播放
    m_statusIndicator->setToolTip("未播放");

    // 标签
    QLabel *restLabel = new QLabel("静息时间:", this);
    restLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    QLabel *stimLabel = new QLabel("刺激时间:", this);
    stimLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    QLabel *repeatLabel = new QLabel("循环次数:", this);
    repeatLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    // 美化开始按钮
    m_startButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_MediaPlay));
    m_startButton->setObjectName("startButton");
    m_startButton->setMinimumWidth(100);

    // 文件选择布局
    QGroupBox *fileGroupBox = new QGroupBox("音频文件", this);
    QVBoxLayout *fileGroupLayout = new QVBoxLayout(fileGroupBox);

    QHBoxLayout *fileLayout = new QHBoxLayout();
    fileLayout->addWidget(m_fileEdit);
    fileLayout->addWidget(m_fileButton);

    // 音量控制布局
    QHBoxLayout *volumeLayout = new QHBoxLayout();
    volumeLayout->addWidget(m_volumeLabel);
    volumeLayout->addWidget(m_volumeSlider);

    fileGroupLayout->addLayout(fileLayout);
    fileGroupLayout->addLayout(volumeLayout);

    // 配置布局
    QGroupBox *configGroupBox = new QGroupBox("播放设置", this);
    QGridLayout *configLayout = new QGridLayout(configGroupBox);

    configLayout->addWidget(restLabel, 0, 0);
    configLayout->addWidget(m_restSpin, 0, 1);
    configLayout->addWidget(stimLabel, 1, 0);
    configLayout->addWidget(m_stimSpin, 1, 1);
    configLayout->addWidget(repeatLabel, 2, 0);
    configLayout->addWidget(m_repeatSpin, 2, 1);

    QHBoxLayout *buttonsLayout = new QHBoxLayout();
    buttonsLayout->addWidget(m_startButton);
    buttonsLayout->addWidget(m_startStimulusButton);
    buttonsLayout->addWidget(m_stopStimulusButton);

    configLayout->addLayout(buttonsLayout, 3, 0, 1, 2);

    // 创建音频播放组
    QGroupBox *audioGroupBox = new QGroupBox("音频刺激播放", this);
    QVBoxLayout *audioLayout = new QVBoxLayout(audioGroupBox);
    audioLayout->addWidget(fileGroupBox);
    audioLayout->addWidget(configGroupBox);

    // 设置文字转语音UI
    setupTtsUi();

    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(audioGroupBox);

    // 创建文字转语音组
    QGroupBox *ttsGroupBox = new QGroupBox("文字转语音", this);
    QVBoxLayout *ttsLayout = new QVBoxLayout(ttsGroupBox);

    // 文本编辑区
    m_textEdit->setPlaceholderText("输入要转换为语音的文字...");
    m_textEdit->setMinimumHeight(100);
    m_textEdit->setObjectName("textEdit");

    // 按钮布局
    QHBoxLayout *ttsBtnLayout = new QHBoxLayout();
    m_speakButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_MediaVolume));
    m_speakButton->setObjectName("speakButton");

    m_stopSpeakButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_MediaStop));
    m_stopSpeakButton->setObjectName("stopSpeakButton");

    ttsBtnLayout->addStretch();
    ttsBtnLayout->addWidget(m_speakButton);
    ttsBtnLayout->addWidget(m_stopSpeakButton);
    ttsBtnLayout->addStretch();

    // 状态标签
    m_ttsStatusLabel->setAlignment(Qt::AlignCenter);
    m_ttsStatusLabel->setObjectName("ttsStatusLabel");
    m_ttsStatusLabel->setStyleSheet("font-weight: bold; color: #2980b9;");

    // 添加到TTS布局
    ttsLayout->addWidget(m_textEdit);
    ttsLayout->addLayout(ttsBtnLayout);
    ttsLayout->addWidget(m_ttsStatusLabel);

    // 添加TTS组到主布局
    mainLayout->addWidget(ttsGroupBox);

    // 添加进度条和状态指示器到主布局底部
    QLabel *progressLabel = new QLabel("刺激进度:", this);
    progressLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);

    QHBoxLayout *progressLayout = new QHBoxLayout();
    progressLayout->addWidget(progressLabel);
    progressLayout->addWidget(m_statusIndicator);
    progressLayout->addWidget(m_progressBar);

    mainLayout->addLayout(progressLayout);

    // 设置主布局
    setLayout(mainLayout);

    // 连接信号槽
    connect(m_fileButton, &QPushButton::clicked, this, &AudioPlayerWidget::onSelectFile);
    connect(m_startButton, &QPushButton::clicked, this, &AudioPlayerWidget::onStartStop);
    connect(m_startStimulusButton, &QPushButton::clicked, this, &AudioPlayerWidget::onStartStimulus);
    connect(m_stopStimulusButton, &QPushButton::clicked, this, &AudioPlayerWidget::onStopStimulus);
    connect(m_player, &QMediaPlayer::playbackStateChanged,
            this, &AudioPlayerWidget::onPlaybackStateChanged);
    connect(&m_restTimer, &QTimer::timeout, this, &AudioPlayerWidget::playStimulus);
    connect(&m_stimTimer, &QTimer::timeout, this, &AudioPlayerWidget::stopStimulus);
    connect(m_volumeSlider, &QSlider::valueChanged, this, &AudioPlayerWidget::onVolumeChanged);

    // 连接TTS相关信号槽
    connect(m_speakButton, &QPushButton::clicked, this, &AudioPlayerWidget::onSpeakText);
    connect(m_stopSpeakButton, &QPushButton::clicked, this, &AudioPlayerWidget::onStopSpeaking);
    connect(m_ttsManager, &TextToSpeechManager::stateChanged, this, &AudioPlayerWidget::onTtsStateChanged);

    // 连接进度更新定时器
    connect(&m_progressTimer, &QTimer::timeout, this, &AudioPlayerWidget::updateProgressBar);

    m_restTimer.setSingleShot(true);
    m_stimTimer.setSingleShot(true);
    m_progressTimer.setInterval(100); // 每100毫秒更新一次进度

    // 在构造函数末尾添加，初始时检查是否有音频文件
    // 如果没有音频文件，则禁用开始刺激按钮
    m_startStimulusButton->setEnabled(!m_fileEdit->text().isEmpty());

    // 应用样式
    this->setStyleSheet(R"(
        QGroupBox {
            border: 1px solid #bdc3c7;
            border-radius: 6px;
            margin-top: 1ex;
            font-weight: bold;
            background-color: rgba(255, 255, 255, 180);
        }

        QGroupBox::title {
            subcontrol-origin: margin;
            subcontrol-position: top center;
            padding: 0 5px;
            color: #2980b9;
        }

        QPushButton#speakButton, QPushButton#startButton, QPushButton#startStimulusButton {
            background-color: #2ecc71;
            color: white;
        }

        QPushButton#speakButton:hover, QPushButton#startButton:hover, QPushButton#startStimulusButton:hover {
            background-color: #27ae60;
        }

        QPushButton#stopSpeakButton, QPushButton#stopStimulusButton {
            background-color: #e74c3c;
            color: white;
        }

        QPushButton#stopSpeakButton:hover, QPushButton#stopStimulusButton:hover {
            background-color: #c0392b;
        }

        QLineEdit, QTextEdit {
            border: 1px solid #bdc3c7;
            border-radius: 4px;
            padding: 4px;
            background-color: white;
        }

        QSlider::groove:horizontal {
            border: 1px solid #bdc3c7;
            height: 8px;
            background: #ecf0f1;
            margin: 2px 0;
            border-radius: 4px;
        }

        QSlider::handle:horizontal {
            background: #3498db;
            border: 1px solid #2980b9;
            width: 18px;
            margin: -2px 0;
            border-radius: 9px;
        }

        QSlider::sub-page:horizontal {
            background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0,
                stop: 0 #3498db, stop: 1 #2980b9);
            border: 1px solid #2980b9;
            height: 8px;
            border-radius: 4px;
        }

        QSpinBox {
            border: 1px solid #bdc3c7;
            border-radius: 4px;
            padding: 4px;
            background-color: white;
        }

        QProgressBar {
            border: 1px solid #bdc3c7;
            border-radius: 4px;
            text-align: center;
            background-color: #ecf0f1;
        }

        QProgressBar::chunk {
            background-color: #3498db;
            width: 10px;
            margin: 0.5px;
        }
    )");
}

void AudioPlayerWidget::setupTtsUi() {
    // 初始化TTS控件状态
    m_stopSpeakButton->setEnabled(false);
}

// 更新状态指示器
void AudioPlayerWidget::updateStatusIndicator() {
    switch (m_stimulusState) {
    case StimulusState::Idle:
        m_statusIndicator->setStyleSheet("background-color: #a0a0a0; border-radius: 12px;"); // 灰色
        m_statusIndicator->setToolTip("未播放");
        break;
    case StimulusState::Stimulating:
        m_statusIndicator->setStyleSheet("background-color: #e74c3c; border-radius: 12px;"); // 红色
        m_statusIndicator->setToolTip("刺激中");
        m_progressBar->setStyleSheet("QProgressBar::chunk { background-color: #e74c3c; }"); // 红色进度条
        break;
    case StimulusState::Resting:
        m_statusIndicator->setStyleSheet("background-color: #3498db; border-radius: 12px;"); // 蓝色
        m_statusIndicator->setToolTip("静息中");
        m_progressBar->setStyleSheet("QProgressBar::chunk { background-color: #3498db; }"); // 蓝色进度条
        break;
    }

    // 发送状态变化信号
    emit stimulusStateChanged(m_stimulusState);
}

// 获取当前刺激状态
StimulusState AudioPlayerWidget::getStimulusState() const {
    return m_stimulusState;
}

// 获取进度
int AudioPlayerWidget::getStimulusProgress() const {
    return m_currentProgress;
}

void AudioPlayerWidget::onStartStimulus() {
    // 检查是否设置了音频文件
    if (m_fileEdit->text().isEmpty()) {
        QMessageBox::warning(this, "提示", "请先选择音频文件");
        return;
    }

    // 如果已经在刺激或静息中，则停止
    if (m_stimulusState != StimulusState::Idle) {
        // 停止所有计时器
        m_restTimer.stop();
        m_stimTimer.stop();
        m_progressTimer.stop();
        m_player->stop();

        // 重置状态和UI
        m_stimulusState = StimulusState::Idle;
        m_startStimulusButton->setText("开始刺激");
        m_progressBar->setValue(0);
        m_progressBar->setFormat("%v%");
        m_currentProgress = 0;

        // 更新按钮状态
        m_startStimulusButton->setEnabled(true);
        m_stopStimulusButton->setEnabled(false);

        // 更新状态指示器
        updateStatusIndicator();

        emit audioEvent("stimulus_stop", QDateTime::currentMSecsSinceEpoch());
        return;
    }

    // 确保音频文件已加载
    if (m_player->source().isEmpty()) {
        m_player->setSource(QUrl::fromLocalFile(m_fileEdit->text()));
    }

    // 计算总持续时间（刺激时间 + 静息时间）
    int stimTime = m_stimSpin->value() * 1000; // 转换为毫秒
    int restTime = m_restSpin->value() * 1000; // 转换为毫秒
    m_totalDuration = stimTime + restTime;
    m_remainingTime = m_totalDuration;

    // 开始刺激
    m_startStimulusButton->setText("停止刺激");
    m_stimulusState = StimulusState::Stimulating;

    // 更新按钮状态
    m_startStimulusButton->setEnabled(false);
    m_stopStimulusButton->setEnabled(true);

    updateStatusIndicator();

    // 发送事件通知
    qint64 timestamp = QDateTime::currentMSecsSinceEpoch();
    emit audioEvent("stimulus_start", timestamp);

    // 开始播放音频 - 修改这里，不自动播放音频
    // m_player->setPosition(0);
    // m_player->play();

    // 设置刺激结束计时器
    m_stimTimer.start(stimTime);

    // 启动进度更新定时器
    m_progressTimer.start();

    // 更新进度条初始状态
    m_progressBar->setFormat("刺激中: %p%");
}

// 新增：停止刺激方法
void AudioPlayerWidget::onStopStimulus() {
    // 调用开始刺激方法，它会处理停止逻辑
    if (m_stimulusState != StimulusState::Idle) {
        // 停止所有计时器
        m_restTimer.stop();
        m_stimTimer.stop();
        m_progressTimer.stop();
        m_player->stop();

        // 重置状态和UI
        m_stimulusState = StimulusState::Idle;
        m_startStimulusButton->setText("开始刺激");
        m_progressBar->setValue(0);
        m_progressBar->setFormat("%v%");
        m_currentProgress = 0;

        // 更新按钮状态
        m_startStimulusButton->setEnabled(true);
        m_stopStimulusButton->setEnabled(false);

        // 更新状态指示器
        updateStatusIndicator();

        // 记录刺激结束时间
        qint64 timestamp = QDateTime::currentMSecsSinceEpoch();
        emit audioEvent("stimulus_stop", timestamp);

        // 更新状态栏消息（通过信号实现）
        // 由于我们已经将功能从MainWindow移到这里，状态栏消息可以通过信号通知MainWindow
    }
}

void AudioPlayerWidget::updateProgressBar() {
    if (m_stimulusState == StimulusState::Idle) {
        return;
    }

    // 减少剩余时间
    m_remainingTime -= 100; // 100毫秒

    // 计算进度百分比
    m_currentProgress = 100 - (m_remainingTime * 100 / m_totalDuration);
    m_progressBar->setValue(m_currentProgress);

    // 发送进度变化信号
    emit stimulusProgressChanged(m_currentProgress);

    // 如果剩余时间小于等于0，停止计时器
    if (m_remainingTime <= 0) {
        m_progressTimer.stop();
        m_progressBar->setValue(100);
        m_currentProgress = 100;
    }
}

void AudioPlayerWidget::onSpeakText() {
    QString text = m_textEdit->toPlainText().trimmed();
    if (text.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入要播放的文字");
        return;
    }

    // 停止当前正在播放的音频
    if (m_player->playbackState() == QMediaPlayer::PlayingState) {
        m_player->stop();
    }

    // 播放文字
    m_ttsManager->speak(text);

    // 更新UI状态
    m_speakButton->setEnabled(false);
    m_stopSpeakButton->setEnabled(true);
    m_ttsStatusLabel->setText("正在播放...");

    // 记录事件
    emit audioEvent("tts_start:" + text.left(30) + (text.length() > 30 ? "..." : ""),
                    QDateTime::currentMSecsSinceEpoch());
}

void AudioPlayerWidget::onStopSpeaking() {
    m_ttsManager->stop();

    // 更新UI状态
    m_speakButton->setEnabled(true);
    m_stopSpeakButton->setEnabled(false);
    m_ttsStatusLabel->setText("已停止");

    // 记录事件
    emit audioEvent("tts_stop", QDateTime::currentMSecsSinceEpoch());
}

void AudioPlayerWidget::onTtsStateChanged(QTextToSpeech::State state) {
    switch (state) {
    case QTextToSpeech::Speaking:
        m_ttsStatusLabel->setText("正在播放...");
        m_speakButton->setEnabled(false);
        m_stopSpeakButton->setEnabled(true);
        break;
    case QTextToSpeech::Paused:
        m_ttsStatusLabel->setText("已暂停");
        break;
    case QTextToSpeech::Ready:
        m_ttsStatusLabel->setText("就绪");
        m_speakButton->setEnabled(true);
        m_stopSpeakButton->setEnabled(false);
        break;
    default:
        m_ttsStatusLabel->setText("错误：语音引擎异常");
        m_speakButton->setEnabled(true);
        m_stopSpeakButton->setEnabled(false);
        break;
    }
}

void AudioPlayerWidget::onSelectFile() {
    QString filePath = QFileDialog::getOpenFileName(this, "选择音频文件", QString(), "音频文件 (*.mp3 *.wav *.ogg *.flac)");
    if (!filePath.isEmpty()) {
        m_fileEdit->setText(filePath);
        m_player->setSource(QUrl::fromLocalFile(filePath));

        // 当选择了音频文件后，确保开始刺激按钮可用
        m_startStimulusButton->setEnabled(true);
    }
}

void AudioPlayerWidget::onStartStop() {
    if (m_player->playbackState() == QMediaPlayer::PlayingState || m_restTimer.isActive() || m_stimTimer.isActive()) {
        // 如果正在播放或计时，则停止一切
        m_restTimer.stop();
        m_stimTimer.stop();
        m_player->stop();
        m_startButton->setText("开始");
        m_startButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_MediaPlay));
        m_currentCycle = 0;
        emit audioEvent("stop", QDateTime::currentMSecsSinceEpoch());
    } else {
        if (m_fileEdit->text().isEmpty()) {
            // 使用QMessageBox代替statusBar
            QMessageBox::warning(this, "提示", "请先选择音频文件");
            return; // 未选文件则不执行
        }

        // 确保音频文件已加载
        if (m_player->source().isEmpty()) {
            m_player->setSource(QUrl::fromLocalFile(m_fileEdit->text()));
        }

        // 初始化循环计数并启动第一次静息计时
        m_totalCycles = m_repeatSpin->value();
        m_currentCycle = 0;
        m_startButton->setText("停止");
        m_startButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_MediaStop));
        emit audioEvent("start", QDateTime::currentMSecsSinceEpoch());
        // 立即开始第一个静息计时（先等待静息，再播放）
        int restSec = m_restSpin->value();
        if (restSec > 0) {
            m_restTimer.start(restSec * 1000);
        } else {
            playStimulus(); // 若静息期为0，则直接播放
        }
    }
}

void AudioPlayerWidget::playStimulus() {
    // 开始播放刺激音频
    if (m_player->source().isEmpty() && !m_fileEdit->text().isEmpty()) {
        m_player->setSource(QUrl::fromLocalFile(m_fileEdit->text()));
    }

    // 从头开始播放
    m_player->setPosition(0);
    m_player->play();
    emit audioEvent("stim_start", QDateTime::currentMSecsSinceEpoch());

    // 设定刺激持续时间计时器
    int stimSec = m_stimSpin->value();
    m_stimTimer.start(stimSec * 1000);
}

void AudioPlayerWidget::stopStimulus() {
    // 停止当前刺激音频
    m_player->stop();
    qint64 timestamp = QDateTime::currentMSecsSinceEpoch();
    emit audioEvent("stim_end", timestamp);

    // 如果是通过开始刺激按钮触发的，则开始静息阶段
    if (m_stimulusState == StimulusState::Stimulating) {
        m_stimulusState = StimulusState::Resting;
        updateStatusIndicator();

        // 更新进度条状态
        m_progressBar->setFormat("静息中: %p%");

        // 开始静息计时
        int restTime = m_restSpin->value() * 1000; // 转换为毫秒
        if (restTime > 0) {
            QTimer::singleShot(restTime, this, [this]() {
                // 静息结束
                m_stimulusState = StimulusState::Idle;
                updateStatusIndicator();
                m_startStimulusButton->setText("开始刺激");
                m_progressBar->setValue(100);
                m_progressBar->setFormat("%p%");
                m_progressTimer.stop();

                // 更新按钮状态
                m_startStimulusButton->setEnabled(true);
                m_stopStimulusButton->setEnabled(false);

                qint64 endTimestamp = QDateTime::currentMSecsSinceEpoch();
                emit audioEvent("rest_end", endTimestamp);
            });

            emit audioEvent("rest_start", timestamp);
        } else {
            // 没有静息时间，直接结束
            m_stimulusState = StimulusState::Idle;
            updateStatusIndicator();
            m_startStimulusButton->setText("开始刺激");
            m_progressBar->setValue(100);
            m_progressBar->setFormat("%p%");
            m_progressTimer.stop();

            // 更新按钮状态
            m_startStimulusButton->setEnabled(true);
            m_stopStimulusButton->setEnabled(false);
        }

        return;
    }

    // 以下是原有的循环逻辑
    m_currentCycle++;
    if (m_currentCycle < m_totalCycles) {
        // 若未达到循环次数，启动下一轮静息->刺激
        m_restTimer.start(m_restSpin->value() * 1000);
    } else {
        // 完成所有循环
        m_startButton->setText("开始");
        m_startButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_MediaPlay));
        emit audioEvent("stop", QDateTime::currentMSecsSinceEpoch());
    }
}

void AudioPlayerWidget::onPlaybackStateChanged(QMediaPlayer::PlaybackState state) {
    if (state == QMediaPlayer::StoppedState) {
        // 当音频自然播放结束且stimTimer尚未到时间
        if (m_stimTimer.isActive()) {
            // 音频已经播放完毕，但刺激时间还未结束
            // 如果启用了循环播放，可以在这里重新开始播放
            if (m_loopEnabled) {
                m_player->setPosition(0);
                m_player->play();
            }
        }
    }
}

void AudioPlayerWidget::onVolumeChanged(int value) {
    // 将滑块的值(0-100)转换为音量值(0.0-1.0)
    qreal linearVolume = value / 100.0;
    m_player->audioOutput()->setVolume(linearVolume);
}

// 获取当前音量（0-100）
int AudioPlayerWidget::getVolume() const {
    return m_volumeSlider->value();
}

// 检查是否启用循环播放
bool AudioPlayerWidget::isLoopEnabled() const {
    return m_loopEnabled;
}

// 设置音量（0-100）
void AudioPlayerWidget::setVolume(int volume) {
    if (volume >= 0 && volume <= 100) {
        m_volumeSlider->setValue(volume);
        // onVolumeChanged槽会被自动调用来更新实际音频输出
    }
}

// 设置是否循环播放
void AudioPlayerWidget::setLoopEnabled(bool enabled) {
    m_loopEnabled = enabled;
    if (m_player && m_player->audioOutput()) {
        // 如果需要，这里可以更新播放器的循环设置
    }
}

// 设置播放速率
void AudioPlayerWidget::setPlaybackRate(double rate) {
    if (rate > 0.0) {
        m_playbackRate = rate;
        if (m_player) {
            m_player->setPlaybackRate(rate);
        }
    }
}

// 加载音频文件
bool AudioPlayerWidget::loadAudioFile(const QString &filePath) {
    if (filePath.isEmpty() || !QFile::exists(filePath)) {
        return false;
    }

    m_fileEdit->setText(filePath);
    m_player->setSource(QUrl::fromLocalFile(filePath));
    m_startStimulusButton->setEnabled(true); // 确保按钮可用
    return true;
}

// 显示音频设置对话框
void AudioPlayerWidget::showAudioSettings() {
    // 显示音频刺激设置对话框
    QDialog dialog(this);
    dialog.setWindowTitle("音频刺激设置");
    dialog.setMinimumWidth(500);
    dialog.setMinimumHeight(400);

    // 创建布局
    QVBoxLayout *mainLayout = new QVBoxLayout(&dialog);

    // 设置统一的字体样式
    QFont standardFont("Microsoft YaHei", 10);
    dialog.setFont(standardFont);

    // 创建音频类型选择组
    QGroupBox *audioTypeGroup = new QGroupBox("音频类型", &dialog);
    audioTypeGroup->setFont(standardFont);
    QVBoxLayout *audioTypeLayout = new QVBoxLayout(audioTypeGroup);

    QRadioButton *musicRadio = new QRadioButton("音乐", audioTypeGroup);
    QRadioButton *natureRadio = new QRadioButton("自然声音", audioTypeGroup);
    QRadioButton *guidedRadio = new QRadioButton("引导冥想", audioTypeGroup);
    QRadioButton *customRadio = new QRadioButton("自定义音频", audioTypeGroup);

    // 设置统一字体
    musicRadio->setFont(standardFont);
    natureRadio->setFont(standardFont);
    guidedRadio->setFont(standardFont);
    customRadio->setFont(standardFont);

    // 默认选择音乐
    musicRadio->setChecked(true);

    audioTypeLayout->addWidget(musicRadio);
    audioTypeLayout->addWidget(natureRadio);
    audioTypeLayout->addWidget(guidedRadio);
    audioTypeLayout->addWidget(customRadio);

    mainLayout->addWidget(audioTypeGroup);

    // 创建音频参数设置组
    QGroupBox *audioParamsGroup = new QGroupBox("参数设置", &dialog);
    audioParamsGroup->setFont(standardFont);
    QGridLayout *audioParamsLayout = new QGridLayout(audioParamsGroup);

    // 音量设置
    QLabel *volumeLabel = new QLabel("音量:", audioParamsGroup);
    volumeLabel->setFont(standardFont);
    QSlider *volumeSlider = new QSlider(Qt::Horizontal, audioParamsGroup);
    volumeSlider->setRange(0, 100);
    volumeSlider->setValue(getVolume());
    QLabel *volumeValueLabel = new QLabel(QString::number(volumeSlider->value()) + "%", audioParamsGroup);
    volumeValueLabel->setFont(standardFont);

    // 连接音量滑块信号
    connect(volumeSlider, &QSlider::valueChanged, [volumeValueLabel](int value) {
        volumeValueLabel->setText(QString::number(value) + "%");
    });

    audioParamsLayout->addWidget(volumeLabel, 0, 0);
    audioParamsLayout->addWidget(volumeSlider, 0, 1);
    audioParamsLayout->addWidget(volumeValueLabel, 0, 2);

    // 播放速度设置
    QLabel *speedLabel = new QLabel("播放速度:", audioParamsGroup);
    speedLabel->setFont(standardFont);
    QComboBox *speedComboBox = new QComboBox(audioParamsGroup);
    speedComboBox->setFont(standardFont);
    speedComboBox->addItem("0.5x", 0.5);
    speedComboBox->addItem("0.75x", 0.75);
    speedComboBox->addItem("1.0x", 1.0);
    speedComboBox->addItem("1.25x", 1.25);
    speedComboBox->addItem("1.5x", 1.5);
    speedComboBox->setCurrentIndex(2); // 默认1.0x

    audioParamsLayout->addWidget(speedLabel, 1, 0);
    audioParamsLayout->addWidget(speedComboBox, 1, 1, 1, 2);

    // 循环播放设置
    QCheckBox *loopCheckBox = new QCheckBox("循环播放", audioParamsGroup);
    loopCheckBox->setFont(standardFont);
    loopCheckBox->setChecked(isLoopEnabled());
    audioParamsLayout->addWidget(loopCheckBox, 2, 0, 1, 3);

    mainLayout->addWidget(audioParamsGroup);

    // 创建自定义音频文件选择组
    QGroupBox *customFileGroup = new QGroupBox("自定义音频文件", &dialog);
    customFileGroup->setFont(standardFont);
    QHBoxLayout *customFileLayout = new QHBoxLayout(customFileGroup);

    QLineEdit *filePathEdit = new QLineEdit(customFileGroup);
    filePathEdit->setFont(standardFont);
    filePathEdit->setReadOnly(true);
    filePathEdit->setText(m_fileEdit->text()); // 显示当前文件路径
    QPushButton *browseButton = new QPushButton("浏览...", customFileGroup);
    browseButton->setFont(standardFont);

    customFileLayout->addWidget(filePathEdit);
    customFileLayout->addWidget(browseButton);

    // 连接浏览按钮信号
    connect(browseButton, &QPushButton::clicked, [&filePathEdit, this]() {
        QString filePath = QFileDialog::getOpenFileName(this,
                                                        "选择音频文件",
                                                        QDir::homePath(),
                                                        "音频文件 (*.mp3 *.wav *.ogg *.flac)");
        if (!filePath.isEmpty()) {
            filePathEdit->setText(filePath);
        }
    });

    // 初始禁用自定义文件选择组
    customFileGroup->setEnabled(false);

    // 连接自定义音频单选按钮信号
    connect(customRadio, &QRadioButton::toggled, customFileGroup, &QGroupBox::setEnabled);

    mainLayout->addWidget(customFileGroup);

    // 创建按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    QPushButton *okButton = new QPushButton("确定", &dialog);
    okButton->setFont(standardFont);
    QPushButton *cancelButton = new QPushButton("取消", &dialog);
    cancelButton->setFont(standardFont);

    buttonLayout->addWidget(okButton);
    buttonLayout->addWidget(cancelButton);

    mainLayout->addLayout(buttonLayout);

    // 连接按钮信号
    connect(cancelButton, &QPushButton::clicked, &dialog, &QDialog::reject);
    connect(okButton, &QPushButton::clicked, [&]() {
        // 应用设置到音频播放器部件
        setVolume(volumeSlider->value());
        setLoopEnabled(loopCheckBox->isChecked());
        setPlaybackRate(speedComboBox->currentData().toDouble());

        // 如果选择了自定义音频并且有文件路径
        if (customRadio->isChecked() && !filePathEdit->text().isEmpty()) {
            loadAudioFile(filePathEdit->text());
        }

        dialog.accept();
        // 通知设置已更新可以通过信号实现
    });

    // 显示对话框
    dialog.exec();
}
